package com.hyacinth;

import java.io.*;

/**
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class MyClassLoader extends ClassLoader {

    private final String root;

    public MyClassLoader(String root) {
        this.root = root;
    }


    @Override
    protected Class<?> findClass(String className) throws ClassNotFoundException {
        String fileName = root + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
        byte[] bytes = loadClassData(fileName);
        if (bytes == null) {
            throw new ClassNotFoundException();
        }
        return defineClass(className, bytes, 0, bytes.length);
    }

    private byte[] loadClassData(String fileName) {
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            is = new FileInputStream(new File(fileName));
            baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) {
        MyClassLoader myClassLoader = new MyClassLoader("E:\\IdeaProjects\\aurora\\target\\test-classes\\com\\hyacinth");
        try {
            Class<?> aClass = myClassLoader.loadClass("AuroraServerTest");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
